package com.jw.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @Author jiangwang
 * @Created by 2021/9/26 18:51
 * @Description: TODO
 */
@Controller
public class LoginController
{
    
    @GetMapping(value = "/toLogin")
    public String toLogin()
    {
        return "login";
    }

    @PostMapping("/login")
    public String login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            Model model)
    {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try
        {
            subject.login(token);
            return "index";
        }
        catch (UnknownAccountException uae)
        {
            model.addAttribute("msg", "用户不存在");
            return "login";
        }
        catch (IncorrectCredentialsException ice)
        {
            model.addAttribute("msg", "密码不正确");
            return "login";
        }
    }

    @GetMapping("/logOut")
    public String logOut()
    {
        return "login";
    }

    @GetMapping("/noAuthorization")
    public String noAuthorization()
    {
        return "未经授权，无法访问此页面";
    }
}
